#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>


void *send_to_service(void* argv){
    char *send_buf=malloc(sizeof(char)*1024);
    char client_socket = *(int *)argv;
    memset(send_buf, 0, sizeof(send_buf));
    while (fgets(send_buf,sizeof(send_buf),stdin) != NULL)
    {
        
        send(client_socket, send_buf, strlen(send_buf), 0);
        memset(send_buf, 0, sizeof(send_buf));
    }
    printf("客户端关闭写");
    shutdown(client_socket,SHUT_WR);
    free(send_buf);
}

void *recv_to_service(void* argv){
    char *recv_buf=malloc(sizeof(char)*1024);
    int client_socket = *(int *)argv;

    memset(recv_buf, 0, sizeof(recv_buf));
    while (recv(client_socket, recv_buf, sizeof(recv_buf), 0) > 0)
    {
        write(STDOUT_FILENO, recv_buf, strlen(recv_buf));
        memset(recv_buf, 0, sizeof(recv_buf));
    }
    
    free(recv_buf);
    printf("服务端关闭读");
    shutdown(client_socket,SHUT_RD);

}

int main(int argc, char const *argv[])
{   
    //客户端的socket_in
    struct sockaddr_in client_addr;
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(6666);
    client_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    //服务端的socket_in
    struct sockaddr_in service_addr;
    service_addr.sin_family = AF_INET;
    service_addr.sin_port = htons(8888);
    service_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    //客户端的socket
    int client_socket = socket(AF_INET, SOCK_STREAM, 0);
    //绑定地址和端口
    bind(client_socket, (struct sockaddr*)&client_addr, sizeof(client_addr));
    //连接服务端
    connect(client_socket,(struct sockaddr*)&service_addr, sizeof(service_addr));
    pthread_t send_thread, recv_thread;
    //创建发送和接收线程
    pthread_create(&send_thread, NULL, send_to_service, (void *)&client_socket);
    pthread_create(&recv_thread, NULL, recv_to_service, (void *)&client_socket);
    //等待线程结束
    pthread_join(send_thread, NULL);
    pthread_join(recv_thread, NULL);
    //关闭客户端socket
    close(client_socket);

    return 0;
}
